package com.geek.novel.network

import com.geek.novel.common.Constant
import com.geek.novel.utils.LogCatUtil
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.PrintWriter
import java.net.HttpURLConnection
import java.net.URL

/**
 * Created by  on 2017/8/9.
 */
object HttpReq {

    fun map2String(map: Map<String, String>?): String {
        if (map == null) {
            return ""
        }
        val sb = StringBuffer()
        for ((key, value) in map) {
            sb.append("$key=$value")
            sb.append("&")
        }
        var s = sb.toString()
        if (s.endsWith("&")) {
            s = s.substring(0, s.length - 1)
        }
        return s
    }


    fun getData(urls:String,map: Map<String, String>?): String {

        var ins: InputStream? = null

        val printWriter: PrintWriter
        val baos: ByteArrayOutputStream? = null
        var s = ""


        http@ //88.128.134.71:8080/spt/services/open/clientCdzService/getCharingSite
        try {
            val url = URL(Constant.HTTP_SERVICE_IP + urls)
            val conn = url
                    .openConnection() as HttpURLConnection
            conn.doInput = true
            conn.doOutput = true
            conn.useCaches = false
            conn.connectTimeout = 5000
            conn.requestMethod = "POST"
            conn.connect()

            printWriter = PrintWriter(conn.outputStream)
            LogCatUtil.d("icsp_ws_out", urls)
            val propertie= map2String(map)
            LogCatUtil.d("icsp_ws_out", propertie)
            // 发送请求参数
            printWriter.write(propertie)// post的参数 xx=xx&yy=yy
            printWriter.flush()
            printWriter.close()
            return if (conn.responseCode != 200) {
                "fail" + conn.responseCode
            } else {
                ins = conn.inputStream
    
                if (ins != null){
                    s = ins.bufferedReader().use { it.readText() }
                }
                s
    
            }

        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                if (ins != null)
                    ins.close()
                if (baos != null) {
                    baos.flush()
                    baos.close()
                }

            } catch (e: IOException) {
                e.printStackTrace()
            }
            return s
        }

    }










}